package edu.xidian.onlinedocument.repository.specification;

import edu.xidian.onlinedocument.entity.DocumentData;
import edu.xidian.onlinedocument.entity.UserData;
import edu.xidian.onlinedocument.repository.DocumentJPARepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Component
public class DocumentSpecification {
    private final DocumentJPARepository documentJPARepository;

    @Autowired
    public DocumentSpecification(DocumentJPARepository documentJPARepository) {
        this.documentJPARepository = documentJPARepository;
    }

    public List<DocumentData> findOneDocumentWithUserById(int docId){
        Specification<DocumentData> specification = new Specification<>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                Join<DocumentData, UserData> docWithUser = root.join("userData", JoinType.LEFT);
                Path<Object> docIdPath = docWithUser.get("docId");
                return criteriaBuilder.equal(docIdPath, docId);
            }
        };
        return documentJPARepository.findAll(specification);
    }

    public List<DocumentData> findAllDocumentWithUser(){
        Specification<DocumentData> specification = new Specification<>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                // 注意：root.join("连接字段", 连接方式)中的连接字段指的是DocumentData类中的UserData类型的成员变量的变量名
                Join<DocumentData, UserData> docWithUser = root.join("userData", JoinType.LEFT);
                Predicate p = docWithUser.getOn();
                query.distinct(true);       // 去重
                return p;
            }
        };
        return documentJPARepository.findAll(specification);
    }
}
